import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:flame/events.dart';
import 'package:flutter_flame/worlds/game/GameWorld.dart';

import '../audio/SoundManager.dart';
import '../entity/SpriteAnimationParamEntity.dart';
import '../../../component/SpriteAnimationEntity.dart';

// 阳关
class SunLight extends SpriteAnimationEntity {
  final Function(GameWorld world) onCollected; // 收集
  final double disappearAfter; // 消失时间(秒)
  double lifeTime = 0; // 阳光目前存在时间
  bool isCollected = false; // 是否被收集

  SunLight({
    required Vector2 pos,
    required this.onCollected,
    this.disappearAfter = 5,
  }) : super(SpriteAnimationParamEntity.sunIdle) {
    position = pos;
  }

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    addHitBox(
      scaleHitBoxK: 0.8,
      hitBoxPosition: Vector2.zero(),
    );
    priority = sunPriority;
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (isCollected) return;
    lifeTime += dt;
    if (lifeTime >= disappearAfter) {
      disappear();
    }
  }

  @override
  void onTapDown(TapDownEvent event) {
    collect();
    super.onTapDown(event);
  }

  // 超时自动消失
  void disappear() {
    add(
      OpacityEffect.fadeOut(
        EffectController(duration: 0.5),
        onComplete: () {
          removeFromParent();
        },
      ),
    );
  }

  // 收集阳光
  void collect() {
    if (isCollected) return;
    isCollected = true;
    SoundManager().playCollectSunlight();
    add(
      MoveToEffect(
        Vector2(50, 20),
        EffectController(duration: 0.3),
        onComplete: () {
          onCollected(world);
          removeFromParent();
        },
      ),
    );
  }
}
